<template>
  <div>
    <!-- <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item><span @click="$router.back()">项目列表</span></el-breadcrumb-item>
      <el-breadcrumb-item>新增流程</el-breadcrumb-item>
    </el-breadcrumb> -->
    <layout-header @openTip='openTip' :value="value" @preview="preview" @publish="publish" @select="v => value = v"></layout-header>
    <div style="background-color: #f5f6f6;padding-top: 20px;padding-bottom: 20px;" v-show="value == 'baseSetting'">
      <form-base-setting ref="baseSetting" @nextStep="value = 'processDesign'"></form-base-setting>
    </div>
    <div v-show="value == 'processDesign'" :style="{width:width}" style="position: relative;">
      <my-process-design ref="processDesign"></my-process-design>
    </div>
    <el-dialog
      title="流程规则"
      :visible.sync="dialogVisible"
      width="30%"
      center
      >
      <div style="display: flex;flex-direction: column;">
        <span style="margin-bottom:10px">1.请先选择完接收人再选择审批人</span>
        <span style="margin-bottom:10px">2.请不要让低权限用户审批高权限用户</span>
        <span style="margin-bottom:10px">3.请至少选择一位接收人和至少一位审批人</span>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  //头部
  import LayoutHeader from "@/views/flow/LayoutHeader.vue"
  //基本信息
  import FormBaseSetting from '@/views/flow/FormBaseSetting'
  //流程组件
  import MyProcessDesign from '@/views/flow/MyProcessDesign'
  export default {
    name: "flow",
    components: {
      LayoutHeader,
      FormBaseSetting,
      MyProcessDesign
    },
    data() {
      return {
        value: "baseSetting",
        width: "100%",
        flowTask:[],
        validateFlag:true,
        maxWeight:0,
        minWeight:0,
        dialogVisible:false,
      }
    },
    computed:{
      setup() {
        return this.$store.state.design
      },
    },
    watch:{

    },
    created() {

      this.loadInitFrom()
    },
    methods: {
      publish(){
        this.flowTask=[]
        this.handlerNodes(this.setup.process)
        this.preview()
        this.$nextTick(async ()=>{
          if(!this.validateFlag)return
          let obj={
            flowName: this.setup.formName,
            pId: this.setup.formId,
            describe: this.setup.remark,
            flowTask: this.flowTask,
            id: this.setup.flowId&&this.setup.flowId!='undefined'?this.setup.flowId:null
          }
          console.log(obj)
          let result=await this.$post('/api/create/flow',obj)
          if(result.code==200){
            this.$message.success('流程创建成功')
            this.$router.push('/home/project')
          }else this.$message.error(result.msg)
        })
      },
      openTip(){
        this.dialogVisible=true
      },
      handlerRepeat(list){
        let categoryArr=[]
        let recentCategory=list[0].type
        let arr=[]
        list.map((item,index)=>{
          if(item.type==recentCategory){
            arr.push(item)
          }else{
            categoryArr.push(arr)
            arr=[]
            arr.push(item)
            recentCategory=item.type
          }
          if(index==list.length-1) categoryArr.push(arr)
        })
        let roleIds=[]
        let userIds=[]
        categoryArr.shift()
        categoryArr.forEach(item=>{
          item.forEach(items=>{
            roleIds.push(...items.roleIds)
            userIds.push(...items.uIds)
          })
        })
        if(roleIds.length>0&&roleIds.length!=[...new Set(roleIds)].length) {
          this.$message.warning("请勿重复选择角色")
          return false
        }
        if(userIds.length>0&&userIds.length!=[...new Set(userIds)].length) {
          this.$message.warning("请勿重复选择用户")
          return false
        }
        return true
      },
      preview(){
        this.$nextTick(_=>{
          let res1 = this.$refs['baseSetting'].validate()
          let res2 = this.$refs['processDesign'].validate()
          this.flowTask=[]
          this.handlerNodes(this.setup.process)
          console.log(this.maxWeight,this.minWeight)
          if(this.maxWeight>this.minWeight)  {
            this.minWeight=0
            this.maxWeight=0
            this.$message.warning('低权限用户不能审批高权限用户！')
            this.validateFlag=false
            return
          }
          if(this.flowTask.length==1){
            this.$message.warning('请至少选择一个接收人和一个审批人')
            this.validateFlag=false
            return
          }
          let lastCcIndex=-1
          let firstAprIndex=-1
          let flag=1
          for(let item in this.flowTask){
            if(this.flowTask[item].type=='CC'){
              lastCcIndex=item
            }else if(flag&&this.flowTask[item].type=='APPROVAL') {
              firstAprIndex=item
              flag=0
            }
          }
          if(lastCcIndex==-1) {
            this.$message.warning('请至少选择一位接收人！')
            this.validateFlag=false
            return
          }
          if(firstAprIndex==-1) {
            this.$message.warning('请至少选择一位审批人！')
            this.validateFlag=false
            return
          }
          if(lastCcIndex>firstAprIndex) {
            this.$message.warning('请选择完接收人后再选择审批人！')
            this.validateFlag=false
            return
          }
          if(res1.length != 0){
            this.$message.warning(res1.toString())
            this.validateFlag=false
            return
          }
          if(res2.length != 0){
            this.$message.warning(res2.toString())
            this.validateFlag=false
            return
          }
          this.flowTask.map(item=>{

          })
          this.validateFlag=this.handlerRepeat(this.flowTask)
          if(!this.validateFlag) return
          this.$message.success('校验通过')
          console.log(this.flowTask)
          this.validateFlag=true
        })
      },
      loadInitFrom() {
        let obj={
          formId: this.$route.query.id,
          flowId:this.$route.query.flowId||null,
          formName: "未命名流程",
          formItems: [],
          process: {
            id: "root",
            parentId: null,
            type: "ROOT",
            name: "发起人",
            desc: "admin",
            props: {
              assignedUser: [],
              formPerms: []
            },
            children: {}
          },
          remark: "备注说明"
        }
        this.$store.commit('loadForm', obj)
        this.$store.commit("setNodeMap", new Map())
        this.$store.commit('removeAnalogueTab',"/home/flow")
        this.$nextTick(()=>{
          this.$store.commit('setTabs',{
            name: "/home/flow?id="+this.$route.query.id+"&flowId="+this.$route.query.flowId,
            title: "创建流程"
          })
        })
      },
      handlerNodes(nodes){
        if(nodes.children){
          this.handlerNodes(nodes.children)
        }else return
          let obj={
            type: "",
            uIds:  [],
            roleIds: [],
            startTime: "",
            endTime: "",
            weights:nodes.weight
          }
          obj.type=nodes.type
          if(nodes.type=="APPROVAL"){
            if(nodes.props['assignedType']=="ASSIGN_USER"){
              nodes.props.assignedUser.map(item=>{
                obj.uIds.push(item.id)
              })
            }else{
              nodes.props.role.map(item=>{
                obj.roleIds.push(item.id)
              })
            }
            if(this.minWeight>nodes.weight||this.minWeight==0)this.minWeight=nodes.weight
          }else if(nodes.type=="CC"){
            if(nodes.props.assignedUser[0].type=="ASSIGN_USER"){
              nodes.props.assignedUser.map(item=>{
                obj.uIds.push(item.id)
              })
            }else{
              nodes.props.assignedUser.map(item=>{
                obj.roleIds.push(item.id)
              })
            }
            if(this.maxWeight<nodes.weight)this.maxWeight=nodes.weight
          }
        this.flowTask.unshift(obj)
      }
    }
  }
</script>

<style lang="scss" scoped>
</style>
